package com.hddznet.uniplatform.sm.config.cas;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.hddznet.uniplatform.sm.dto.CasToken;
import com.hddznet.uniplatform.sm.dto.CasUserinfo;
import com.hddznet.uniplatform.sm.dto.UserInfo;
import com.hddznet.uniplatform.sm.service.IUserService;
import com.hddznet.uniplatform.sm.vo.Result;

@Service("casUserDetailsService")
public class CasUserDetailsServiceImpl implements CasUserDetailsService  {

	@Autowired
	private IUserService userService;
 
	@Override
	public UserDetails loadUserByUsername(String code) throws UsernameNotFoundException {

        Result<CasToken> result = userService.getUniwaterCasToken(code);
        if (!result.isSuccess()) {
        	throw new UsernameNotFoundException(result.getMessage());
            //throw new UsernameNotFoundException(String.format("Username not found for cas, code=%s, state=%s",  code, state));
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("user");
		grantedAuthorities.add(grantedAuthority);
        
        //User userDetails = new User(result.getResult().getUserinfo().getAccount(), "test", Collections.emptyList());
		CasUserinfo casUser = result.getResult().getUserinfo();
        UserInfo userDetails = new  UserInfo(casUser.getAccount(), "test", Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, grantedAuthorities);
        userDetails.setId(casUser.getId());
        userDetails.setUserName(casUser.getName());
        userDetails.setGroupId(casUser.getGroup());
        userDetails.setRoles(Arrays.asList(casUser.getRoless()));
		return userDetails;
	}
}